﻿using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json;
using System;

namespace AVCUMPlatform.HelperLibrary.Cache
{
    /// <summary>
    /// 内存缓存
    /// </summary>
    public class MemoryCache : ICache
    {
        /// <summary>
        /// 构造
        /// </summary>
        private MemoryCache() { }
        /// <summary>
        /// 单例
        /// </summary>
        public static MemoryCache Instance { get; } = new MemoryCache();
        /// <summary>
        /// 缓存对象
        /// </summary>
        private static Microsoft.Extensions.Caching.Memory.MemoryCache CacheServer =
            new Microsoft.Extensions.Caching.Memory.MemoryCache(new MemoryCacheOptions());

        /// <summary>
        /// 根据主键获取
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public T Get<T>(string key)
        {
            CacheServer.TryGetValue(key, out string jsonStr);
            if (string.IsNullOrEmpty(jsonStr))
            {
                return default(T);
            }
            return JsonConvert.DeserializeObject<T>(jsonStr);
        }

        /// <summary>
        /// 判断key是否存在
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool IsExists(string key)
        {
            return CacheServer.Get(key) != null;
        }

        /// <summary>
        /// 移除
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool Remove(string key)
        {
            CacheServer.Remove(key);
            return true;
        }

        /// <summary>
        /// 添加缓存
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="expiry"></param>
        /// <param name="isSliding">是否滑动</param>
        /// <returns></returns>
        public bool Set<T>(string key, T value, TimeSpan expiry, bool isSliding = false) where T: class
        {
            string dataStr = JsonConvert.SerializeObject(value);
            CacheServer.Set(key, dataStr, isSliding 
                ? new MemoryCacheEntryOptions().SetSlidingExpiration(expiry)
                : new MemoryCacheEntryOptions().SetAbsoluteExpiration(expiry));
            return true;
        }
    }
}
